package com.jiraonthego.proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;

import com.google.gson.Gson;
import com.jiraonthego.IActivityHandler;
import com.jiraonthego.model.IssueVO;
import com.jiraonthego.model.IssuesListVO;

public class HTTPTask extends AsyncTask <Object, Void, String> {
	
	private IActivityHandler activity;

	@Override
	protected String doInBackground(Object... args) {
		activity = (IActivityHandler) args[0];
		
		HttpsURLConnection connection;
		StringBuilder strBuilder = new StringBuilder();
		try {
			URL obj = new URL(args[1].toString());
			connection = (HttpsURLConnection) obj.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Authorization", args[2].toString());
			
			try {
				InputStream in = connection.getInputStream();
				InputStreamReader is = new InputStreamReader(in);
				BufferedReader br = new BufferedReader(is);
				String read = br.readLine();
	
				while(read != null) {
					strBuilder.append(read);
					read =br.readLine();
				}
				br.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		catch (MalformedURLException e) {
			e.printStackTrace();
	    }
		catch (IOException e) {
			e.printStackTrace();
	    }
		return strBuilder.toString();
	}
	
	
	@Override
    protected void onPostExecute(String result) {
		JSONObject objJSON = new JSONObject();
		try {
			Gson gson = new Gson(); 
			final IssuesListVO user = gson.fromJson(result.toString(), IssuesListVO.class);
			String json = gson.toJson(user);
			objJSON = new JSONObject(result.toString());
		}
		catch(JSONException e) {
			e.printStackTrace();
		}
		activity.resultHandler(objJSON);
    }

}
